package context

import (
	"sen-golang-study/go_game_study/hero_story_go_server/game_server/internal/infrastructure/async"
)

// WebSocketCmdContext WebSocket命令上下文实现
type WebSocketCmdContext struct {
	id            string
	userID        uint32
	clientIPAddr  string
	sessionID     string
	msgChan       chan *async.AsyncResult
}

// NewWebSocketCmdContext 创建WebSocket命令上下文
func NewWebSocketCmdContext(id, clientIPAddr string, msgChan chan *async.AsyncResult) *WebSocketCmdContext {
	return &WebSocketCmdContext{
		id:           id,
		userID:       0,
		clientIPAddr: clientIPAddr,
		sessionID:    "",
		msgChan:      msgChan,
	}
}

// GetID 获取上下文ID
func (ctx *WebSocketCmdContext) GetID() string {
	return ctx.id
}

// SetID 设置上下文ID
func (ctx *WebSocketCmdContext) SetID(id string) {
	ctx.id = id
}

// BindUserID 绑定用户ID
func (ctx *WebSocketCmdContext) BindUserID(userID uint32) {
	ctx.userID = userID
}

// GetUserID 获取用户ID
func (ctx *WebSocketCmdContext) GetUserID() uint32 {
	return ctx.userID
}

// GetClientIPAddr 获取客户端IP地址
func (ctx *WebSocketCmdContext) GetClientIPAddr() string {
	return ctx.clientIPAddr
}

// GetSessionID 获取会话ID
func (ctx *WebSocketCmdContext) GetSessionID() string {
	return ctx.sessionID
}

// SetSessionID 设置会话ID
func (ctx *WebSocketCmdContext) SetSessionID(sessionID string) {
	ctx.sessionID = sessionID
}

// WriteMsg 写入消息
func (ctx *WebSocketCmdContext) WriteMsg(msgCode uint16, msgBody interface{}) {
	if ctx.msgChan == nil {
		return
	}

	// 创建消息结构
	msg := map[string]interface{}{
		"msgCode": msgCode,
		"msgBody": msgBody,
	}

	// 创建异步结果并发送到消息通道
	result := &async.AsyncResult{}
	result.SetReturnValue(msg)

	select {
	case ctx.msgChan <- result:
		// 消息发送成功
	default:
		// 消息通道已满，忽略消息
	}
}

// SendError 发送错误消息
func (ctx *WebSocketCmdContext) SendError(errMsg string) {
	if ctx.msgChan == nil {
		return
	}

	// 创建错误消息结构
	errorMsg := map[string]interface{}{
		"msgCode": uint16(0), // 0表示错误消息
		"msgBody": map[string]interface{}{
			"error": errMsg,
		},
	}

	// 创建异步结果并发送到消息通道
	result := &async.AsyncResult{}
	result.SetReturnValue(errorMsg)

	select {
	case ctx.msgChan <- result:
		// 错误消息发送成功
	default:
		// 消息通道已满，忽略消息
	}
}

// Disconnect 断开连接
func (ctx *WebSocketCmdContext) Disconnect() {
	if ctx.msgChan == nil {
		return
	}

	// 创建断开连接消息
	disconnectMsg := map[string]interface{}{
		"msgCode": uint16(65535), // 65535表示断开连接
		"msgBody": map[string]interface{}{
			"reason": "disconnect",
		},
	}

	// 创建异步结果并发送到消息通道
	result := &async.AsyncResult{}
	result.SetReturnValue(disconnectMsg)

	select {
	case ctx.msgChan <- result:
		// 断开连接消息发送成功
	default:
		// 消息通道已满，忽略消息
	}

	// 关闭消息通道
	close(ctx.msgChan)
	ctx.msgChan = nil
}